package com.manage;

import java.util.ArrayList;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.drawable.BitmapDrawable;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.WindowManager;
import android.view.View.OnClickListener;
import android.widget.AbsListView;
import android.widget.Button;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.ProgressBar;
import android.widget.SimpleCursorAdapter;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.AbsListView.OnScrollListener;

import com.manage.adapter.OrderAdapter;
import com.manage.base.BaseActivity;
import com.manage.db.MenuTypeDBAdapter;
import com.manage.model.OrderItem;
import com.manage.sharedpreferences.SPConfig;
import com.manage.util.RequestUtils;

/**
 * 新增餐品
 * @author liyoro
 *
 */
public class ModifyOrderActivity extends BaseActivity implements OnClickListener, OnScrollListener {

	private static String TAG = "ModifyOrderActivity";
	
	private ListView orderListview = null;
	private ArrayList<OrderItem> orderList = new ArrayList();
	
	//OrderDetailActivity中已有的菜单
	private ArrayList<OrderItem> orderListParent = null;
	private OrderAdapter orderAdapter = null;
	
	private TextView tvSelect = null;
	private PopupWindow selectWindow;
	
	private Button btnSubmit = null;
	
	// 加载
	private View loadingLayout;
	private ProgressBar progressBar;
	private TextView errText;
	
	//分页
	private int lastItem = 0;
	private boolean isEndFlag = false;
	
	@Override
	@SuppressWarnings("unchecked")
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		this.setContentView(R.layout.add_order_list);
		
		// 从OrderDetailActivity返回的数据
		orderListParent = (ArrayList<OrderItem>)getIntent()
				.getSerializableExtra(OrderDetailActivity.SERORDERLIST);
		
		initDatas();
	}

	@Override
	public String getLeftBtnName() {
		return "返回";
	}

	@Override
	public String getTitleName() {
		return "新增菜单";
	}

	@Override
	public boolean showButton() {
		return true;
	}

	@Override
	public void initView() {
		orderListview = (ListView) findViewById(R.id.listview1);

		// 加载更多
		loadingLayout = ((LayoutInflater)ModifyOrderActivity
				  .this.getSystemService(Context.LAYOUT_INFLATER_SERVICE))
				  .inflate(R.layout.more_row, null, false);

		// 加载到listActivity的底部
		orderListview.addFooterView(loadingLayout);

		orderAdapter = new OrderAdapter(this);
		orderAdapter.showEditButton(View.VISIBLE);
		orderListview.setAdapter(orderAdapter);
		orderListview.setOnScrollListener(this);
		
		loadingLayout.setOnClickListener(this);
		loadingLayout.setClickable(false);
		
		progressBar = (ProgressBar)loadingLayout.findViewById(R.id.progressbar);
		errText = (TextView)loadingLayout.findViewById(R.id.err_text);
		
		tvSelect = (TextView)findViewById(R.id.popup_item_pending_accept_msg);
		tvSelect.setOnClickListener(this);
		
		btnSubmit = (Button)findViewById(R.id.btn_submit);
		btnSubmit.setOnClickListener(this);
	}

	public void showProgress() {
		progressBar.setVisibility(View.VISIBLE);
		errText.setText("正在加载数据...");
		
		if(orderListview.getFooterViewsCount() == 0) {
			Log.d(TAG, "listView.getFooterViewsCount() == 0");
			orderListview.addFooterView(loadingLayout);
		}
	}
	
	public void hideProgress() {
		errText.setText("正在加载数据...");
		
		if(orderListview.getFooterViewsCount() != 0) {
			orderListview.removeFooterView(loadingLayout);
		}
	}
	
	public void showAgainProgress() {
		loadingLayout.setClickable(true);
		loadingLayout.setVisibility(View.VISIBLE);
		orderListview.setVisibility(View.VISIBLE);
		progressBar.setVisibility(View.GONE);
		errText.setVisibility(View.VISIBLE);
		errText.setText("获取数据失败，点击重试！");
	}
	
	@Override
	public void initDatas() {
		showProgress();
		orderList.clear(); 

		if(page == 1) {
			orderList.clear();
			orderAdapter.setValue(null);
			orderAdapter.setClear(true);
		} else {
			orderAdapter.setClear(false);
		}

		String shopID = sp.getString(SPConfig.SHOPID, "");
		String token = sp.getString(SPConfig.ACCESSTOKEN, "0");
		String currentSelect = sp.getString(SPConfig.CURRENTMENUTYPE, "0");
		
		if(currentSelect.equals("0")) {
			tvSelect.setText("所有分类");
		} 
		else if(currentSelect.equals("1")) {
			tvSelect.setText("特色推荐");
		} 
		else if(currentSelect.equals("2")){
			tvSelect.setText("盅饭");
		} 
		else if(currentSelect.equals("3")){
			tvSelect.setText("碟头饭");
		} 
		else if(currentSelect.equals("4")){
			tvSelect.setText("肠粉");
		} 
		else if(currentSelect.equals("5")){
			tvSelect.setText("甜品");
		}
		else if(currentSelect.equals("6")){
			tvSelect.setText("粥");
		}
		else if(currentSelect.equals("7")){
			tvSelect.setText("面食");
		}
		
		RequestUtils.getOrderMenu(token, shopID, currentSelect, ADDORDERSURL, String.valueOf(page), handler, this.requestList);
	}
	
	private Handler handler = new Handler() {
		public void handleMessage(Message msg) { 
			switch(msg.what) {
			case SUCCESS:

				if(orderList.size() < 5) {
					hideProgress();
				}
				
				Bundle bundle = msg.getData();
				String res = bundle.getString("res");

				if(res != null && !res.equals("[{}]") && res.length() > 15) {
					try {
						JSONObject temp = new JSONObject(res.substring(1, res.length()-1));
						
						JSONArray tempOrder = new JSONArray(temp.getString("return_info"));
//						Log.i(TAG, tempOrder.toString());
						
//						ArrayList<OrderItem> dishesList = new ArrayList();
						
						for(int i=0; i<tempOrder.length(); i++) {
							OrderItem dish = new OrderItem();
							
							JSONObject temp4 = new JSONObject(tempOrder.getString(i));
							dish.setCaipin_ID(temp4.getString("dishes_id"));
							dish.setCaipin_name(temp4.getString("name"));
							dish.setCaipin_price(temp4.getString("price"));
							dish.setType_ID(temp4.getString("type_id"));
							dish.setRecommend(temp4.getString("recommend"));
							
							orderList.add(dish);
						}
						orderAdapter.setValue(orderList);
						
					} catch (JSONException e) {
						e.printStackTrace();
					}
							
				} else {
					isEndFlag = true;
					hideProgress();
					Toast.makeText(ModifyOrderActivity.this, "已经是最后一页", 
							Toast.LENGTH_SHORT).show();
				}
				
				break;
			case FAIL:
				showAgainProgress();
				break;
			}
		}
	};
	
	@Override
	public void onScroll(AbsListView view, int firstVisibleItem,
			int visibleItemCount, int totalItemCount) {
		lastItem = firstVisibleItem + visibleItemCount-1;
	}

	@Override
	public void onScrollStateChanged(AbsListView view, int scrollState) {
		if(true == isEndFlag){
			return;
		}
		showProgress();
		
		if (lastItem == orderAdapter.getCount() 
				&& scrollState == OnScrollListener.SCROLL_STATE_IDLE) {
			page++;
//			Log.d(TAG, "nowpage:" + page);
			initDatas();
		}
	}

	/**
	 * 订单状态选项dialog
	 * 1:待受理订单，2：待配送订单，3：待入账订单，4：已完成,5:已取消
	 * @author liyoro
	 *
	 */
	private void showSelectPop(View parent) {
		View view = null;
		ListView mListview = null;
		
//		TextView item_all_sort = null;
//		TextView item_recommend = null;
//		TextView item_zhongfan = null;
//		TextView item_dietoufan = null;
//		TextView item_changfen = null;
//		TextView item_tianpin = null;
//		TextView item_zhou = null;
//		TextView item_mianshi = null;
		
		LayoutInflater layoutInflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
		view = layoutInflater.inflate(R.layout.popup_win_list, null);
		mListview = (ListView)view.findViewById(R.id.popup_view);
		
		MenuTypeDBAdapter mDBAdapter = new MenuTypeDBAdapter(ModifyOrderActivity.this);
		mDBAdapter.open();
		Cursor cursor = mDBAdapter.fetchAllData();
		Log.i(TAG, "aaaaaaaaa:"+cursor.getCount());
		startManagingCursor(cursor);
		mDBAdapter.close();
	         
	    ListAdapter listAdapter = new SimpleCursorAdapter(this, R.layout.popup_win_list_item, 
	                cursor,
	                new String[]{"sort"}, 
	                new int[]{R.id.tv_all_sort});
	         
	    mListview.setAdapter(listAdapter);
	        
		// 创建一个PopuWidow对象
		selectWindow = new PopupWindow(view, 200, 510);
		
		// 使其聚集
		selectWindow.setFocusable(true);
		
		// 设置允许在外点击消失
		selectWindow.setOutsideTouchable(true);
		
		// 这个是为了点击“返回Back”也能使其消失，并且并不会影响你的背景
		selectWindow.setBackgroundDrawable(new BitmapDrawable());
		
		WindowManager windowManager = (WindowManager) getSystemService(Context.WINDOW_SERVICE);
		// 显示的位置为:屏幕的宽度的一半-PopupWindow的高度的一半
		int xPos = ((windowManager.getDefaultDisplay().getWidth()-50)/ 4)
				- selectWindow.getWidth() / 2;
		selectWindow.showAsDropDown(parent, xPos, 0);
		
//		item_all_sort = (TextView)view.findViewById(R.id.tv_all_sort);
//		item_recommend = (TextView)view.findViewById(R.id.tv_recommend);
//		item_zhongfan = (TextView)view.findViewById(R.id.tv_zhongfan);
//		item_dietoufan = (TextView)view.findViewById(R.id.tv_dietoufan);
//		item_changfen = (TextView)view.findViewById(R.id.tv_changfen);
//		item_tianpin = (TextView)view.findViewById(R.id.tv_tianpin);
//		item_zhou = (TextView)view.findViewById(R.id.tv_zhou);
//		item_mianshi = (TextView)view.findViewById(R.id.tv_mianshi);
        
        View.OnClickListener _selectListener = new View.OnClickListener() {
			
			@Override
			public void onClick(View v) {
				switch(v.getId()) {
				case R.id.tv_all_sort:
					tvSelect.setText("所有分类");
					sp.setString(SPConfig.CURRENTMENUTYPE, "0");
					page = 1;
					initDatas();
					selectWindow.dismiss();
					break;
				case R.id.tv_recommend:
					tvSelect.setText("特色推荐");
					sp.setString(SPConfig.CURRENTMENUTYPE, "1");
					page = 1;
					initDatas();
					selectWindow.dismiss();
					break;
				case R.id.tv_zhongfan:
					tvSelect.setText("盅饭");
					sp.setString(SPConfig.CURRENTMENUTYPE, "2");
					page = 1;
					initDatas();
					selectWindow.dismiss();
					break;
				case R.id.tv_dietoufan:
					tvSelect.setText("碟头饭");
					sp.setString(SPConfig.CURRENTMENUTYPE, "3");
					page = 1;
					initDatas();
					selectWindow.dismiss();
					break;
				case R.id.tv_changfen:
					tvSelect.setText("肠粉");
					sp.setString(SPConfig.CURRENTMENUTYPE, "4");
					page = 1;
					initDatas();
					selectWindow.dismiss();
					break;
				case R.id.tv_tianpin:
					tvSelect.setText("甜品");
					sp.setString(SPConfig.CURRENTMENUTYPE, "5");
					page = 1;
					initDatas();
					selectWindow.dismiss();
					break;
				case R.id.tv_zhou:
					tvSelect.setText("粥");
					sp.setString(SPConfig.CURRENTMENUTYPE, "6");
					page = 1;
					initDatas();
					selectWindow.dismiss();
					break;
				case R.id.tv_mianshi:
					tvSelect.setText("面食");
					sp.setString(SPConfig.CURRENTMENUTYPE, "7");
					page = 1;
					initDatas();
					selectWindow.dismiss();
					break;
				}
			}
		};
		
//		item_all_sort.setOnClickListener(_selectListener);
//		item_recommend.setOnClickListener(_selectListener);
//		item_zhongfan.setOnClickListener(_selectListener);
//		item_dietoufan.setOnClickListener(_selectListener);
//		item_changfen.setOnClickListener(_selectListener);
//		item_tianpin.setOnClickListener(_selectListener);
//		item_zhou.setOnClickListener(_selectListener);
//		item_mianshi.setOnClickListener(_selectListener);
	}
	
	@Override
	public void onClick(View v) {
		switch(v.getId()) {
		case R.id.popup_item_pending_accept_msg:
			showSelectPop(tvSelect);
			break;
		case R.id.more_self:
			initDatas();
			break;
		case R.id.btn_submit:
			for(int i=0; i<orderList.size(); i++) {
				OrderItem dish = orderList.get(i);
				if(Integer.valueOf(dish.getCaipin_count()) > 0) {
//					for(int j=0; j< orderListParent.size(); j++) {
//						OrderItem dishParent = orderListParent.get(j);
//						
//						if(dish.getCaipin_ID().equals(dishParent.getCaipin_ID())) {
//							
//							int count = Integer.valueOf(dishParent.getCaipin_count()) + 1;
//							dishParent.setCaipin_count(String.valueOf(count));
//						} else {
							orderListParent.add(dish);
//						}
//					}
					
				}
			}
			compare(orderListParent);
			Intent mIntent = new Intent(); 

//			Log.i(TAG, "btn_submit:"+orderListParent.size());
			Bundle mBundle = new Bundle();
			mBundle.putSerializable(OrderDetailActivity.SERORDERLIST, orderListParent);
			
			mIntent.putExtras(mBundle); 
			
			ModifyOrderActivity.this.setResult(ADDORDERMENUS, mIntent);  
            ModifyOrderActivity.this.finish();  
            
			break;
		}
	}
	
	/**
	 * 对于相同的item，count+1就ok了
	 * @param listParent
	 */
	private void compare(ArrayList<OrderItem> listParent) {
		for(int i=0; i<listParent.size(); i++) {
			OrderItem dishParent = listParent.get(i);
			
			for(int j=listParent.size()-1; j>i; j--) {
				OrderItem dishParent2 = listParent.get(j);
				
				if(dishParent.getCaipin_ID().equals(dishParent2.getCaipin_ID())) {
					int count = Integer.valueOf(dishParent.getCaipin_count()) + 1;
					dishParent.setCaipin_count(String.valueOf(count));
					listParent.remove(j);
				}
			}
		}
//		Log.i(TAG, "btn_submit:" + listParent.size());
	}
}
